/**
 * 管理员任务管理路由
 *
 * Created by yangyunze on 2020/03/12.
 */
const middleware = require('./../middleware');
const tasks = require('./../../models/tasks');
const users = require('./../../models/users');
const PhoenixError = require('./../../models/phoenix-error');
const files = require('../../models/files');

/**
 * 批量获取任务列表
 * @param req
 * @param res
 * @param next
 */
function getTasks(req, res, next) {
  const resTasks = {
    pagination: req.filter,
  };
  let tasksList;
  const options = tasks.getTaskOptions(req.query);
  tasks.filter(req.filter, options)
    .then((data) => {
      tasksList = data;
      return users.getUsers({ userIds: data.map((task) => task.creatorId) });
    })
    .then((users) => {
      const usersMap = new Map();
      users.forEach((user) => {
        usersMap.set(user._id.toString(), user.username);
      });
      resTasks.tasks = tasksList.map((task) => {
        if (usersMap.has(task.creatorId.toString())) {
          task.tester = usersMap.get(task.creatorId.toString());
        }
        return tasks.getJson(task);
      });
      return tasks.getCount(options);
    })
    .then((count) => {
      resTasks.pagination.total = count;
      res.json(resTasks);
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 获取任务信息
 * @param req
 * @param res
 * @param next
 */
function getTask(req, res, next) { // eslint-disable-line no-unused-vars
  (async () => {
    const { fileIds } = req.$task;
    const filesArr = await files.getFilesByIds(fileIds, {
      projection: {
        fileId: '$_id',
        fileName: 1,
        _id: 0,
      },
    });
    res.json(Object.assign(tasks.getJson(req.$task), { files: filesArr }));
  })()
    .catch((err) => next(new PhoenixError(err)));
}

/**
 * 编辑任务
 * @param req
 * @param res
 * @param next
 */
function updateTask(req, res, next) {
  const { taskId } = req.params;
  tasks.updateTask(taskId, req.query)
    .then(() => tasks.getTask(taskId))
    .then((task) => {
      res.json(tasks.getJson(task));
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 批量编辑任务
 * @param req
 * @param res
 * @param next
 */
function updateTasks(req, res, next) {
  tasks.updateTasks(null, req.query)
    .then(() => {
      res.status(202).json();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const taskURL = `${prefix}/tasks/:taskId.json`;
  const tasksURL = `${prefix}/tasks.json`;

  // 获取任务列表
  app.get(tasksURL, middleware.user.requireTokenUnexpired);
  app.get(tasksURL, middleware.user.requireAvailable);
  app.get(tasksURL, middleware.user.requireAdministrator);
  app.get(tasksURL, middleware.splitFilter);
  app.get(tasksURL, getTasks);

  // 编辑任务
  app.put(taskURL, middleware.user.requireTokenUnexpired);
  app.put(taskURL, middleware.user.requireAvailable);
  app.put(taskURL, middleware.user.requireAdministrator);
  app.put(taskURL, middleware.task.requireTaskExist);
  app.put(taskURL, updateTask);

  // 获取任务
  app.get(taskURL, middleware.user.requireTokenUnexpired);
  app.get(taskURL, middleware.user.requireAvailable);
  app.get(taskURL, middleware.user.requireAdministrator);
  app.get(taskURL, middleware.task.requireTaskExist);
  app.get(taskURL, getTask);

  // 批量编辑任务列表
  app.put(tasksURL, middleware.user.requireTokenUnexpired);
  app.put(tasksURL, middleware.user.requireAvailable);
  app.put(tasksURL, middleware.user.requireAdministrator);
  app.put(tasksURL, updateTasks);
};
